<template>
  <basic-container class="app-container-groupmangerment">
    <div class="filter-group">
      <el-form ref="form" :model="groupmanagementFrom" label-width="80px">
        <div class="flexfilter">
          <el-form-item label="后台单号:">
            <el-input
              v-model.trim="groupmanagementFrom.xmbzNo"
              clearable
              placeholder="请选择后台单号"
              class="filter-item"
              size="small"
              @keyup.enter.native="handleFilter(Launchdate)"
            />
          </el-form-item>
          <!-- <el-form-item label="平台单号:">
            <el-input v-model.trim="groupmanagementFrom.platformOrderId" clearable placeholder="请选择平台单号"
              class="filter-item" size="small" @keyup.enter.native="handleFilter" />
          </el-form-item>-->
          <el-form-item label="地区:">
            <el-select
              ref="mainWarehouseRef"
              v-model="groupmanagementFrom.mainWarehouse"
              placeholder="请选择地区"  
              class="filter-item"
              size="small"
              @change="getmainWarehouseIds"
              @keydown.native="selectBlur($event)"
            >
              <el-option
                v-for="item in mainWarehousesList"
                :key="item.id"
                :label="item.deptName"
                :value="{ label: item.deptName, value: item.id }"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="分仓:">
            <el-select
              ref="barnchWarehousesRef"
              v-model="barnchWarehousesName"
              placeholder="请选择分仓"
              class="filter-item"
              size="small"
              @change="getbarnchWarehouses"
              @keydown.native="selectBlur($event)"
            >
              <el-option
                v-for="item in barnchWarehousesList"
                :key="item.id"
                :label="item.name"
                :value="{ label: item.name, value: item.id }"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="订单状态:">
            <el-select
              ref="statusNameRef"
              v-model="statusName"
              placeholder="请选择订单状态"
              clearable
              class="filter-item"
              size="small"
              @visible-change="getstatus"
              @change="getstatusIds"
              @keydown.native="selectBlur($event)"
            >
              <el-option
                v-for="item in OrderStatus"
                :key="item.statusId"
                :label="item.status"
                :value="{ label: item.status, value: item.statusId }"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="分配状态:">
            <el-select
              ref="deliveryRef"
              v-model="deliveryStatus"
              placeholder="请选择分配状态"
              clearable
              class="filter-item"
              size="small"
              @change="getdeliveryStatusIds"
              @keydown.native="selectBlur($event)"
            >
              <el-option
                v-for="item in deliveryStatusList"
                :key="item.status"
                :label="item.name"
                :value="{ label: item.name, value: item.status }"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="是否跳舞:">
            <el-select
              ref="danceRef"
              v-model="groupmanagementFrom.isDance"
              placeholder="请选择"
              clearable
              class="filter-item"
              size="small"
              @keydown.native="selectBlur($event)"
            >
              <el-option
                v-for="item in chooseDance"
                :key="item.status"
                :label="item.name"
                :value="item.status"
              />
            </el-select>
          </el-form-item>
        </div>
        <div class="flexfilter">
          <el-form-item label="配送时间:">
            <!-- <el-date-picker v-model="Launchdate" type="datetimerange" size="small" :default-time="['00:00:00', '23:59:00']"
              range-separator="至" start-placeholder="开始时间" end-placeholder="结束时间" :clearable='false'>
            </el-date-picker>-->
            <el-date-picker
              v-model="Launchdate"
              type="datetimerange"
              range-separator="至"
              start-placeholder="开始时间"
              end-placeholder="结束时间"
              size="small"
              :default-time="['00:00:00', '23:59:59']"
              value-format="yyyy-MM-dd HH:mm"
              format="yyyy-MM-dd HH:mm"
              :clearable="false"
              align="right"
            ></el-date-picker>
          </el-form-item>
          <el-form-item>
            <div class="filter-btns">
              <el-button
                type="primary"
                class="filter-item"
                icon="el-icon-search"
                size="small"
                @click="handleFilter(Launchdate)"
                plain
                >查询
              </el-button>
              <el-button
                type="success"
                onkeydown="if(event.keyCode==13){event.keyCode=0;event.returnValue=false;}"
                class="filter-item"
                icon="el-icon-truck"
                size="small"
                @click="handleistribution"
                plain
                >选择配送员
              </el-button>

              <el-button
                type="warning"
                onkeydown="if(event.keyCode==13){event.keyCode=0;event.returnValue=false;}"
                class="filter-item"
                icon="el-icon-truck"
                size="small"
                @click="showUUOrderPanel()"
                plain
                >第三方物流
              </el-button>
            </div>
            <statistics ref="statistics"></statistics>
          </el-form-item>
          <!-- <el-form-item>
            <abnormalWorkOrder :warehouseId="groupmanagementFrom.warehouseId"></abnormalWorkOrder>
          </el-form-item> -->
        </div>
        <!-- <div class="flexfilter">

        </div>-->
      </el-form>
    </div>
    <div class="group-main">
      <div class="left" :style="{ height: curHeight + 'px' }">
        <el-table
          ref="multipleTable"
          :data="groupmanagementFromlist"
          tooltip-effect="dark"
          border=""
          fit
          highlight-current-row
          @selection-change="handleSelectionChange"
          :height="curHeight + 'px'"
        >
          <el-table-column
            type="selection"
            min-width="30"
            fixed
            align="center"
          ></el-table-column>
          <el-table-column
            label="后台单号"
            prop="xmbzNo"
            align="left"
            min-width="74px"
          >
            <template slot-scope="{ row }">
              <span
                style="white-space: nowrap; cursor: pointer"
                @click="xmbzNoPosition(row)"
                >{{ row.xmbzNo }}</span
              >
            </template>
          </el-table-column>
          <!-- <el-table-column label="平台单号" prop="id" align="left" width="120px">
            <template slot-scope="{row}">
              <span>{{ row.platformOrderId }}</span>
            </template>
          </el-table-column>-->
          <el-table-column label="分仓" prop="id" align="left" min-width="70px">
            <template slot-scope="{ row }">
              <span>{{ row.branchWarehouse }}</span>
            </template>
          </el-table-column>
          <el-table-column
            label="配送时间"
            prop="timestamp"
            align="left"
            min-width="92px"
          >
            <template slot-scope="{ row }">
              <span>{{ row.deliveryTime }}</span>
            </template>
          </el-table-column>
          <el-table-column
            label="配送员"
            prop="id"
            align="center"
            min-width="68px"
          >
            <template slot-scope="{ row }">
              <span>{{ row.delivery }}</span>
            </template>
          </el-table-column>

          <el-table-column
            label="平台仓"
            prop="id"
            align="center"
            min-width="68px"
          >
            <template slot-scope="{ row }">
              <span>{{ row.platformWarehouse }}</span>
            </template>
          </el-table-column>
        </el-table>
        <!-- <pagination v-show="total>0" :total="total" :page.sync="groupmanagementFrom.page" :limit.sync="groupmanagementFrom.size"
        layout="sizes,prev, pager, next,total" @pagination="getList" />-->
      </div>
      <div class="map" :style="{ height: curHeight + 'px' }">
        <mapLegend class="map-legend"></mapLegend>
        <div class="Selectedorderlist" @click="handleSelectedorderlist">
          <el-badge :value="this.multipleSelection.length" class="item">
            <img
              src="https://oss.cdn.xiongmaodangao.com/3431637682213_.pic_hd.jpg"
            />
            选中订单列表
          </el-badge>
        </div>
        <XmMap :options="{id: 'groupmanagementMap'}" ref="xmMap" style="width: 100%;height: 100%"></XmMap>
      </div>
    </div>
    <el-dialog
      title="配送员"
      :visible.sync="dialogDistributorVisible"
      width="width"
      lock-scroll
    >
      <el-button
        type="warning"
        plain
        size="small"
        style="margin-bottom: 10px"
        v-model="delivery"
        @click="handledeliverys(deliveriesList)"
        >清空选中
      </el-button>
      <div
        v-for="(itemmain, key, index) in deliveriesList"
        :key="index"
        style="width: 100%"
        class="deliveriesList"
      >
        <div class="deliveryperson">{{ key }}</div>
        <div class="delivery-item">
          <span
            v-for="item in itemmain"
            :key="item.index"
            :class="{ active: item.isSelected == 1 }"
            @click="handledistror(item, deliveriesList)"
            >{{ item.name }}</span
          >
        </div>
      </div>
      <span slot="footer" class="dialog-footer" v-if="saveflag">
        <el-button type="primary" @click="handelsaveOrder">保存</el-button>
      </span>
      <span slot="footer" class="dialog-footer" v-else>
        <el-button @click="dialogDistributorVisible = false">取 消</el-button>
        <el-button
          :loading="distributing"
          type="primary"
          @click="handelDistributeDeliveryForOrder(deliveriesList)"
          >分配</el-button
        >
      </span>
    </el-dialog>
    <el-dialog
      title="选中订单列表"
      :visible.sync="dialogSelectedorderVisible"
      width="60%"
      lock-scroll
    >
      <el-table
        ref="multipleSelection"
        :data="multipleSelection"
        style="width: 100%"
        @selection-change="handleSelectionChangeData"
      >
        <el-table-column type="selection" width="44"></el-table-column>
        <el-table-column
          prop="xmbzNo"
          label="后台单号"
          width="180"
        ></el-table-column>
        <el-table-column
          prop="platformOrderId"
          label="平台单号"
          width="180"
        ></el-table-column>
        <el-table-column
          prop="branchWarehouse"
          label="分仓"
          width="180"
        ></el-table-column>
        <el-table-column prop="deliveryTime" label="配送时间"></el-table-column>
        <el-table-column prop="delivery" label="配送员"></el-table-column>
      </el-table>
      <span slot="footer" class="dialog-footer">
        <el-button type="danger" @click="handleDelSelectedorder"
          >删除</el-button
        >
        <el-button type="primary" @click="dialogSelectedorderVisible = false"
          >取消</el-button
        >
      </span>
    </el-dialog>
    <orderInfoDialog ref="orderInfoDialog"></orderInfoDialog>
    <!-- 在这修改成京东物流订单列表 -->
    <otherDeliveryDialog ref="otherDeliveryDialog" @submit="updateListAfterRelease"></otherDeliveryDialog>
  </basic-container>
</template>
<script>
import {
  getOrderForDelivery,
  getMainWarehouseList,
  getSeparateWarehouseList,
  getOrderStatus,
  getdeliveriesList,
  distributeDeliveryForOrderDispatch,
  getWarehouseList,
  getOrderInfo,
} from "@/api/orderDispatch";
import Pagination from "@/components/Pagination"; // secondary package based on el-pagination
import selecteds from "@/assets/image/selecteds.png";
import mapLegend from "@/views/scheduling/components/mapLegend";
import statistics from "@/views/scheduling/components/statistics";
import { icons } from "@/const";
import abnormalWorkOrder from './components/abnormalWorkOrder'
import orderInfoDialog from '@/components/order/orderInfoDialog'
import AMap from 'AMap'
import otherDeliveryDialog from './components/otherDeliveryDialog'
function getMarkerIcon(item) {
  if (item.isDelivery == 0) {
    if (item.isDance == 0) {
      return icons["marker-yellow"];
    } else {
      return icons["marker-red"];
    }
  } else if (item.isDelivery == 1) {
    return icons["marker-green"];
  }
  console.log("unknow：" + item.name);
  return icons["marker-red"];
}
function getMarkerLabel(item) {
  return `${item.isDance == 0 ? "不跳舞|" : ""}${item.xmbzNo}|${
    item.deliveryTime
  }${item.delivery ? `|${item.delivery}` : ""}`;
}
var mapSelectData = []

export default {
  components: {
    Pagination,
    mapLegend,
    statistics,
    abnormalWorkOrder,
    orderInfoDialog,
    otherDeliveryDialog,
  },
  data() {
    return {
      // 公共部分--------------------------------------------------------------------------------
      selecteds,
      mainWarehousesList: [], //地区
      deliveryStatusList: [
        {
          //配送分配
          name: "全部",
          status: "",
        },
        {
          name: "未分配",
          status: 0,
        },
        {
          name: "已分配",
          status: 1,
        },
      ],
      chooseDance: [
        {
          name: "跳舞",
          status: 1,
        },
        {
          name: "不跳舞",
          status: 0,
        },
        {
          name: "不确定",
          status: 2,
        },
      ],
      barnchWarehousesList: [], //分仓列表
      deliveryStatusIds: "", //分配状态的ID
      deliveryStatus: "",
      OrderStatus: [], //订单状态
      statusIds: "", //订单状态
      statusName: "",
      delivery: "", //配送员

      // 列表数据--------------------------------------------------------------------------------
      groupmanagementFrom: {
        deptId: "",
        xmbzNo: "", // 订单号
        platformOrderId: "", //平台单号
        mainWarehouse: "全部", //地区
        warehouseId: "", //分仓
        isDance: "", // 选择是否跳舞
        deliveryStatus: "", //分配状态 0:未分配 1:已分配
        deliveryStartTime: this.dayjs(new Date())
          .format("YYYY-MM-DD HH:mm:ss")
          .toString(), //配送开始时间
        deliveryEndTime: this.dayjs()
          .add(3, "hour")
          .format("YYYY-MM-DD HH:59:ss")
          .toString(),
        //配送结束时间
        // page: 1,
        // size: 10
      },
      barnchWarehousesName: "全部",
      Launchdate: [
        this.dayjs(new Date()).format("YYYY-MM-DD HH:mm:ss").toString(),
        this.dayjs().add(3, "hour").format("YYYY-MM-DD HH:59:ss").toString(),
      ],
      groupmanagementFromlist: [],
      total: 0,
      multipleSelection: [], //多选数据
      // 地图数据--------------------------------------------------------------------------------
      // 配送员
      dialogDistributorVisible: false,
      deliveriesList: [],
      // 选中订单列表
      dialogSelectedorderVisible: false,
      cityareaId: "",

      childSelectItems: [],
      WarehouseListData: [],
      curHeight: 0,
      saveflag: false,
      distributing: false,
    };
  },
  created() {
    this.beforeMount(240);
  },
  mounted() {
    console.log(this)
    var saberareaIds = JSON.parse(localStorage.getItem("saber-areaId"));
    this.cityareaId = saberareaIds["content"];
    this.mainWarehouse();
    this.barnchWarehouses();
    this.beforeMount(240);
    this.getList();
    this.getWarehouseListData();

    if (
      this.dialogDistributorVisible == false &&
      this.dialogSelectedorderVisible == false
    ) {
      window.addEventListener("keydown", this.keyupEnter);
    } else {
      window.removeEventListener("keydown", this.keyDown, false);
    }
  },
  // 销毁事件
  destroyed() {
    window.removeEventListener("keydown", this.keyDown, false);
  },
  methods: {
    // 公共部分--------------------------------------------------------------------------------
    // 选择框回车失焦
    selectBlur(e) {
      if (e.keyCode == 13) {
        this.$refs["mainWarehouseRef"].blur();
        this.$refs["barnchWarehousesRef"].blur();
        this.$refs["statusNameRef"].blur();
        this.$refs["deliveryRef"].blur();
        e.returnValue = false;
      }
    },
    // 回车事件
    keyupEnter() {
      if (
        this.dialogDistributorVisible == false &&
        this.dialogSelectedorderVisible == false
      ) {
        if (window.event.keyCode == 13) {
          this.handleFilter(this.Launchdate); // 查询事件
        }
      } else {
        window.removeEventListener("keydown", this.keyDown, false);
      }
    },
    //如果页面有keep-alive缓存功能，这个函数会触发
    activated() {
      window.addEventListener("keydown", this.keyupEnter);
    },
    deactivated() {
      window.removeEventListener("keydown", this.keyupEnter);
    },
    //获取屏幕
    beforeMount(height) {
      var h =
        document.documentElement.clientHeight || document.body.clientHeight;
      this.curHeight = h - height; //减去页面上固定高度height
    },
    mainWarehouse() {
      getMainWarehouseList({
        parentId: this.cityareaId,
      }).then((response) => {
        response.data.data.unshift({
          id: "",
          deptName: "全部",
        });
        this.mainWarehousesList = response.data.data;
        this.mainWarehouseIds = response.data.data[0].id;
        this.mainWarehouseNames = response.data.data[0].deptName;
        this.groupmanagementFrom.mainWarehouse = response.data.data[0].deptName;
      });
    },
    getmainWarehouseIds(data) {
      if (this.groupmanagementFrom.mainWarehouse == "全部") {
        this.productionQuery.mainWarehouse = "";
        this.mainWarehouseNames = "";
        this.mainWarehouseIds = "";
        this.barnchWarehouses();
      } else {
        this.groupmanagementFrom.mainWarehouse = data.label;
        this.mainWarehouseNames = data.label;
        this.mainWarehouseIds = data.value;
        this.barnchWarehouses();
      }
      // this.groupmanagementFrom.mainWarehouse = data.label;
      //  this.mainWarehouseNames= data.label;
      // this.mainWarehouseIds = data.value;
      this.barnchWarehousesName = "全部";
      this.groupmanagementFrom.warehouseId = "";
    },

    getdeliveryStatusIds(data) {
      if (data) {
        this.deliveryStatusIds = data.value;
      } else {
        this.deliveryStatusIds = "";
        this.groupmanagementFrom.deliveryStatusIds = "";
      }
    },
    barnchWarehouses() {
      // if (
      //   this.groupmanagementFrom.mainWarehouse == "" ||
      //   this.mainWarehouseIds == null ||
      //   this.mainWarehouseIds == "undefined"
      // ) {
      //   this.$message({
      //     showClose: true,
      //     message: "请选择地区",
      //     type: "warning"
      //   });
      // } else {
      var saberareaIds = JSON.parse(localStorage.getItem("saber-areaId"));
      this.cityareaId = saberareaIds["content"];
      getSeparateWarehouseList({
        cityId: this.cityareaId,
        deptId: this.mainWarehouseIds == "" ? "" : this.mainWarehouseIds,
      }).then((response) => {
        response.data.data.unshift({
          id: "",
          name: "全部",
        });
        this.barnchWarehousesList = response.data.data;
        this.mainWarehouseIds = response.data.data[0].id;
        this.barnchWarehousesName = response.data.data[0].name;
        this.groupmanagementFrom.warehouseId = response.data.data[0].id;
      });
      // }
    },
    getbarnchWarehouses(data) {
      this.groupmanagementFrom.warehouseId = data.value;
      this.barnchWarehousesName = data.label;
    },
    getstatusIds(data) {
      if (data) {
        this.statusIds = data.value;
        this.statusName = data.label;
      } else {
        this.statusIds = "";
        this.groupmanagementFrom.status = "";
        this.statusName = "";
      }
    },
    getstatus() {
      //订单状态
      getOrderStatus("").then((res) => {
        this.OrderStatus = res.data.data;
      });
    },
    //列表--------------------------------------------------------------------------------
    getList() {
      //列表
      this.groupmanagementFrom.deptId = this.cityareaId;
      (this.groupmanagementFrom.deliveryStartTime = this.dayjs(
        this.groupmanagementFrom.deliveryStartTime
      )
        .format("YYYY-MM-DD HH:mm:00")
        .toString()), //配送开始时间
        (this.groupmanagementFrom.deliveryEndTime = this.dayjs(
          this.groupmanagementFrom.deliveryEndTime
        )
          .format("YYYY-MM-DD HH:mm:59")
          .toString()), //配送结束时间

      this.groupmanagementFrom.mainWarehouse =
        this.mainWarehouseNames == "全部" ? "" : this.mainWarehouseNames;
      return getOrderForDelivery(this.groupmanagementFrom).then((response) => {
        this.groupmanagementFromlist = response.data.data;
        this.groupmanagementFromlist.map((item) => {
          item.checked = false;
        });
        setTimeout(() => {
          this.getShowmap(this.groupmanagementFromlist);
          this.$refs.xmMap.setCenterByOverlays()
        }, 0.1 * 1000);
        if (this.groupmanagementFrom.mainWarehouse == "") {
          this.groupmanagementFrom.mainWarehouse = "全部";
          this.mainWarehouseNames = "";
        }
        this.$refs.statistics &&
          this.$refs.statistics.getData(this.groupmanagementFrom);
      });
    },
    getWarehouseListData() {
      getWarehouseList({
        deptId: this.cityareaId,
      }).then((response) => {
        this.WarehouseListData = response.data.data;
        this.ShowWarehouse(this.WarehouseListData, this.$refs.xmMap.map);
      });
    },
    //查询订单
    handleFilter(times) {
      //查询
      // this.groupmanagementFrom.page = 1;
      this.groupmanagementFrom.mainWarehouse = this.mainWarehouseNames;
      this.groupmanagementFrom.deliveryStatus = this.deliveryStatusIds;
      this.groupmanagementFrom.status = this.statusIds;
      if (times) {
        this.groupmanagementFrom.deliveryStartTime = this.dayjs(times[0])
          .format("YYYY-MM-DD HH:mm:ss")
          .toString();
        this.groupmanagementFrom.deliveryEndTime = this.dayjs(times[1])
          .format("YYYY-MM-DD HH:mm:ss")
          .toString();
      }
      var time1 = Date.parse(this.groupmanagementFrom.deliveryStartTime);
      var time2 = Date.parse(this.groupmanagementFrom.deliveryEndTime);
      this.groupmanagementFrom.mainWarehouse =
        this.mainWarehouseNames == "全部" ? "" : this.mainWarehouseNames;
      //讲两个时间相减，求出相隔的天数
      var dayCount = Math.abs(time2 - time1) / 1000 / 60 / 60 / 24;
      if (dayCount > 31) {
        this.$message({
          showClose: true,
          message: "时间间隔不可超过31天",
          type: "warning",
        });
      } else {
        this.$refs.xmMap.map.clearMap();
        this.getList();
        this.getWarehouseListData();
      }
    },
    // 选择订单
    handleSelectionChange(val) {
      this.multipleSelection = val;
      this.groupmanagementFromlist.map((item) => {
        item.checked = false;
        this.multipleSelection.map((child) => {
          child.checked = true;
        });
      });
    },

    // 选中订单列表
    handleSelectedorderlist() {
      this.dialogSelectedorderVisible = true;
    },
    // 选中订单列表选择
    handleSelectionChangeData(value) {
      this.childSelectItems = value;
    },
    //配送员------------------------------------------------------------------------------
    handleistribution() {
      if (this.multipleSelection.length === 0) {
        this.$message.warning("请选择至少一张订单");
        return;
      } else {
        for (let i = 0; i < this.multipleSelection.length; i++) {
          let item = this.multipleSelection[i];
          if (item.delivery &&
              (item.delivery.includes('达达') || item.delivery.includes('顺丰'))) {
            this.$message.warning("第三方物流订单需要取消后才能修改配送员");
            return;
          }
        }
        this.dialogDistributorVisible = true;
        let ids = [];
        this.multipleSelection.map((item) => {
          ids.push(item.xmbzNo);
        });
        const selectData = {
          xmbzNos: ids.join(","),
          deptId: this.cityareaId,
        };
        getdeliveriesList(selectData).then((response) => {
          this.deliveriesList = response.data.data;
          let isSelectedlist = [];
          for (let warp in this.deliveriesList) {
            this.deliveriesList[warp].map((item) => {
              if (item.isSelected == "1") {
                isSelectedlist.push(item);
              }
            });
          }
          if (isSelectedlist.length > 0) {
            this.saveflag = false;
          } else {
            this.saveflag = true;
          }
        });
      }
    },
    showUUOrderPanel() {
      if (this.multipleSelection.length === 0) {
        this.$message.warning("请选择至少一张订单");
        return;
      } else {
        this.$refs.otherDeliveryDialog.show(this.multipleSelection)
      }
    },
    updateListAfterRelease() {
      const selections = this.multipleSelection.map(s => s.xmbzNo)
      const uuSelections = this.$refs.uuMultipleSelection.selection.map(s => s.xmbzNo)
      this.getList().then(() => {
        this.groupmanagementFromlist.forEach(row => {
          if (selections.includes(row.xmbzNo)) {
            this.$refs.multipleTable.toggleRowSelection(row, true)
          }
        })
        this.$nextTick(() => {
          this.multipleSelection.forEach(row => {
            if (uuSelections.includes(row.xmbzNo)) {
              this.$refs.uuMultipleSelection.toggleRowSelection(row, true)
            }
          })
        })
      })
    },
    //清空配送员
    handledeliverys(list) {
      this.saveflag = true;
      for (let warp in list) {
        list[warp].map((item) => {
          item.isSelected = 0;
        });
      }
      this.delivery = "";
    },

    // 选择配送员
    handledistror(sel, list) {
      this.saveflag = false;
      for (let warp in list) {
        list[warp].map((item) => {
          item.isSelected = 0;
          if (sel.name === item.name) {
            item.isSelected = 1;
          }
        });
      }
      this.delivery = sel.name;
    },
    //分配
    handelDistributeDeliveryForOrder(list) {
      let isSelectedlist = [];
      for (let warp in list) {
        list[warp].map((item) => {
          if (item.isSelected == "1") {
            isSelectedlist.push(item);
          }
        });
      }
      if (this.multipleSelection.length === 0) {
        this.$message.warning("请选择至少一张订单");
        return;
      }
      if (isSelectedlist.length > 1) {
        this.$message.warning("不能同时分配给多个配送员");
        return;
      }
      let ids = [];
      this.multipleSelection.map((item) => {
        ids.push(item.id);
      });
      const selectData = {
        ids: ids,
        account: this.delivery == "" ? isSelectedlist[0].name : this.delivery,
      };
      this.distributing = true;
      distributeDeliveryForOrderDispatch(selectData).then(() => {
        this.$notify({
          title: "成功",
          message: "添加配送员成功",
          type: "success",
          duration: 2000,
        });
        this.dialogDistributorVisible = false;
        setTimeout(() => {
          this.getList();
        }, 0.1 * 1000);
      }).finally(() => {
        this.distributing = false;
      });
    },
    handelsaveOrder() {
      let ids = [];
      this.multipleSelection.map((item) => {
        ids.push(item.id);
      });
      const selectData = {
        ids: ids,
        account: this.delivery,
      };
      distributeDeliveryForOrderDispatch(selectData).then(() => {
        this.$notify({
          title: "提示",
          message: "该订单的配送员已清空",
          type: "warning",
        });
        this.$refs.xmMap.map.clearMap();
        this.dialogDistributorVisible = false;
        setTimeout(() => {
          this.getList();
          this.getWarehouseListData();
        }, 0.1 * 1000);
      });
    },

    // 删除选择订单
    handleDelSelectedorder() {
      this.$confirm("确定删除选中数据？ 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          const child = this.childSelectItems;
          child.forEach((row) => {
            this.$refs.multipleTable.toggleRowSelection(row);
          });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
    },
    // 地图 ---------------------------------------------------------- -----------------------------
    // 显示仓库范围（圆圈）
    ShowWarehouse(warehouseData, map) {
      for (var i = 0; i < warehouseData.length; i++) {
        let circle = new AMap.Circle({
          center: [warehouseData[i].longitude, warehouseData[i].latitude], // 圆心位置
          radius: 500, //半径
          strokeColor: "#F33", //线颜色
          strokeOpacity: 1, //线透明度
          strokeWeight: 3, //线粗细度
          fillColor: "#ee2200", //填充颜色
          fillOpacity: 0.35, //填充透明度
        });
        map.add([circle]);
        let mar = new AMap.Marker({
          map: map,
          position: [warehouseData[i].longitude, warehouseData[i].latitude],
          offset: new AMap.Pixel(-20, -20),
          icon: "https://oss.cdn.xiongmaodangao.com/14581637683413_.pic_hd.jpg",
          size: new AMap.Size(10, 10), //图标所处区域大小
          imageSize: new AMap.Size(10, 10), //图标大小
        });
        mar.setLabel({
          //修改label相对于maker的位置
          offset: new AMap.Pixel(-20, -20),
          content: warehouseData[i].address,
        });
      }
    },
    //显示分配与未分配
    getShowmap(item) {
      let self = this;
      document.oncontextmenu = function () {
        /*阻止浏览器默认弹框*/
        return false;
      };
      for (var i = 0; i < item.length; i++) {
        // 已处理为“绿色”，未处理为“红色”，选中为“蓝色”最新
        //yi分组，未分配 显示绿色
        var myIcon = new AMap.Marker({
          position: [item[i].longitude, item[i].latitude],
          icon: getMarkerIcon(item[i]),
        });
        myIcon.setLabel({
          //修改label相对于maker的位置
          offset: new AMap.Pixel(-20, -20),
          content: getMarkerLabel(item[i]),
          backgroundColor: "0.00001",
        });

        myIcon.item = item[i];
        myIcon.id = item[i].xmbzNo;
        this.$refs.xmMap.map.add(myIcon);
        myIcon.on("rightclick", function (items) {
          getOrderInfo({
            orderId: items.target.item.id,
          }).then((res) => {
            self.$refs.orderInfoDialog.show(res.data.data)
          });
        });
        myIcon.on("click", function (items) {
          var eid = items.target.id;
          if (mapSelectData.indexOf(eid) == -1) {
            //看看里面有没有这个点如果没有，就改点的颜色为选中状态，并把订单号记录进去
            this.setIcon(icons["marker-blue"]);
            self.addMapList(eid, this.item);
          } else {
            //说明有这个单，就取消掉这个单，把点的颜色改为没有选中的状态，green
            //去掉数据
            this.setIcon(getMarkerIcon(this.item));
            self.delMapList(eid, items);
          }
        });
      }
    },

    //添加
    addMapList(id, items) {
      mapSelectData.push(id);
      this.$refs.multipleTable.toggleRowSelection(items);
    },
    //删除
    delMapList(id, items) {
      this.$refs.multipleTable.toggleRowSelection(items.target.item);
      var index = mapSelectData.indexOf(id);
      if (index > -1) {
        mapSelectData.splice(index, 1);
      }
    },
    xmbzNoPosition(item) {
      this.$refs.xmMap.map.setZoomAndCenter(19, [
        item.longitude,
        item.latitude,
      ]);
    },
  },
};
</script>

<style lang="scss" scoped>
.app-container-groupmangerment {
  padding: 10px 5px 10px 10px;
  box-sizing: border-box;

  .filter-group {
    .flexfilter {
      display: flex;

      .formitem {
        width: 640px;
      }
    }

    .el-form-item {
      margin-bottom: 10px !important;
    }

    .filter-btns {
      display: inline-flex;
      align-items: center;
    }
  }

  tr.map_act {
    color: red !important;
    background-color: #fff !important;
  }

  .group-main {
    display: flex;

    .left {
      overflow-y: auto;
      margin-right: 20px;

      .el-table .cell {
        padding: 0 5px !important;
      }

      .el-table td,
      .el-table th {
        padding: 8px 0 !important;
      }
    }

    .map {
      flex: auto;
      position: relative;

      .amap-marker-label {
        border: 1px solid blue !important;
        padding: 3px !important;
        background-color: #fff;
      }

      .map-legend {
        position: absolute;
        z-index: 2;
        right: 30px;
        bottom: 10px;
      }

      .Selectedorderlist {
        padding-left: 8px;
        position: absolute;
        z-index: 2;
        top: 30px;
        right: 30px;
        border-radius: 4px;
        width: 140px;
        background-color: #409eff;
        box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
        line-height: 40px;
        color: #fff;

        img {
          width: 24px;
          height: 24px;
          vertical-align: middle;
        }
      }
    }
  }

  .deliveriesList {
    border-top: 1px solid #ebeef5;
    display: flex;
    line-height: 44px;

    .deliveryperson {
      margin-right: 10px;
    }

    .delivery-item {
      cursor: pointer;
      /* padding-left: 20px; */
      display: flex;
      flex: 1;
      width: 50%;
      flex-wrap: wrap;

      span {
        width: 90px;

        text-align: center;

        &.active {
          width: 77px;
          height: 32px;
          line-height: 17px;
          border-radius: 3px;
          background-color: rgba(238, 248, 232, 1);
          color: rgba(122, 199, 86, 1);
          font-size: 12px;
          text-align: left;
          font-family: Roboto;
          border: 1px solid rgba(122, 199, 86, 1);
          text-align: center;
          line-height: 32px;
          margin-top: 6px;
        }
      }
    }

    &:last-child {
      border-bottom: 1px solid #ebeef5;
    }
  }
}
</style>
